import router from './router'
import store from './store'

// 导入进度条插件
import NProgress from 'nprogress'
// 导入进度条样式
import 'nprogress/nprogress.css'

import getPageTitle from '@/utils/get-page-title'

// 白名单
const whiteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  // 设置网页标题
  document.title = getPageTitle(to.meta.title)
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      await store.dispatch('user/getUserInfoActions')
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
})

// 后置路由守卫
router.afterEach((to, from) => {
  // 隐藏进度条效果
  NProgress.done()
})
